let baseURL = 'https://bee.teamotto.cn/api/';
let imageURL = 'https://bee.teamotto.cn';
let version = __wxConfig.envVersion;
// console.log("version", version);
if (version === 'develop') {
  // baseURL = 'http://192.168.1.182:5173/massage';
}

const request = (url, method, data, header = {}) => {
  let requestTask;
  const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJhdWQiOiIiLCJpYXQiOjE3NjAxNTA1MTUsIm5iZiI6MTc2MDE1MDUxNSwiZXhwIjoxNzYyNzQyNTE1LCJkYXRhIjp7Im9wZW5pZCI6MX19.c72F3whaPEsNOlc5YLRJSYsQg4gyB2UCgItQx1nf9YI'; // 获取存储的 token
  const promise = new Promise((resolve, reject) => {
    requestTask = wx.request({
      url: `${baseURL}${url}`,
      method: method,
      data: data,
      header: {
        // 'Content-Type': 'application/json',
        'access-token': token, // 添加 token
        'Cookie': `token=${token}`,
        ...header
      },
      // timeout: 10000,
      success: (res) => {
        if (res.data.code === 200) {
          resolve(res.data);
        }else {

          // 处理非200的状态码
          handleError(res);
          reject(res);
        }
      },
      fail: (err) => {
        console.log(err);
        // if (err.errMsg !== "request:fail abort") {
        //   handleError(err);
        //   reject(err);
        // }
      }
    });
  });

  // 将 requestTask 作为 promise 的中断方法返回
  promise.abort = () => {
    requestTask.abort();
  };
  return promise;
};

const get = (url, data = {}, header = {}) => {
  return request(url, 'GET', data, header);
};

const post = (url, data = {}, header = {}) => {
  return request(url, 'POST', data, header);
};

const handleError = (error) => {
  console.log("error", error);
  // 统一错误处理
  setTimeout(() => {
    wx.hideLoading();
  }, 10);
  if(error.data.code!=101){
    setTimeout(() => {
      wx.showToast({
        title: error.data.message || error.data.msg || '请求失败', // 显示错误信息
        icon: 'none',
        duration: 2000,
      });
    }, 20);
  }
};

module.exports = {
  get,
  post,
  baseURL,
  imageURL
};